# -*- coding: UTF-8 -*-
"""
@File    ：file_define.py
@Author  ：techPang
@Date    ：2025/2/6 16:57 
@Version ：1.0

和文件相关的类
"""
import json

from data_define import Record


# 先定义顶层抽象类，用来做顶层设计，确定有那些功能需要完成
class FileReader:
    def read_date(self) -> list[Record]:
        """读取文件的数据，读到的每一条数据都转换为Record对象，将他们都封装到list内返回即可"""
        pass


# 文本类型读取
class TextFileReader(FileReader):

    def __init__(self, path):
        self.path = path

    def read_date(self) -> list[Record]:
        f = open(self.path, 'r', encoding='utf-8')

        # 定义一个空的record集合用来存放record
        record_list: list[Record] = []

        for line in f.readlines():
            # 去除前后空格和换行
            line = line.strip()
            data_list = line.split(",")
            # 封装为对象
            record = Record(
                date=data_list[0],
                order_id=data_list[1],
                money=int(data_list[2]),
                province=data_list[3]
            )
            # 添加到集合中
            record_list.append(record)

        # 关闭文件
        f.close()
        return record_list


# Json类型读取
class JsonFileReader(FileReader):
    def __init__(self, path):
        self.path = path

    def read_date(self) -> list[Record]:
        f = open(self.path, 'r', encoding='utf-8')

        # 定义一个空的record集合用来存放record
        record_list: list[Record] = []

        for line in f.readlines():
            line = line.strip()
            # 将json转为map
            data_map = json.loads(line)
            record = Record(
                date=data_map.get("date"),
                order_id=data_map['order_id'],
                money=int(data_map['money']),
                province=data_map['province']
            )
            record_list.append(record)

        f.close()
        return record_list


if __name__ == '__main__':
    reader = JsonFileReader('./2011年2月销售数据JSON.txt')
    json_list = reader.read_date()
    for data in json_list:
        print(data)

    reader1 = TextFileReader('./2011年1月销售数据.txt')
    text_list = reader1.read_date()
    for data in text_list:
        print(data)
